package com.zhku.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhku.entity.Appointable_list;
import com.zhku.entity.Appointment;
import com.zhku.entity.User;
import com.zhku.entity.Vaccinum;
import com.zhku.openservice.UserOpenService;
import com.zhku.openservice.VacciOpenService;
import com.zhku.service.IAppointableListService;
import com.zhku.service.IAppointmentService;
import com.zhku.service.IVaccinumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 疫苗预约 前端控制器
 * </p>
 *
 * @author dewey
 * @since 2023-03-31
 */
@RestController
@RequestMapping(value = "/appointment")
public class AppointmentController {
    // 预约记录
    @Autowired
    IAppointmentService appointmentService;

    @Autowired
    IAppointableListService appointableListService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IVaccinumService vaccinumService;

    @Autowired
    VacciOpenService vacciOpenService;

    @Autowired
    UserOpenService userOpenService;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @description: 用来带参数，查询符合的预约信息
     * @author: deweyMDH
     * @param: [pageNum, pageSize, keyword]
     * @return: java.lang.String
     **/
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(
            @RequestParam(required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(required = true, defaultValue = "1") Integer pageSize,
            @RequestParam(required = false, defaultValue = "") String keyword,  //关键词
            @RequestParam(required = false, defaultValue = "") String condition
    ) throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
        //分页查询
        /* 分页构造函数
        Params:
        current – 当前页
        size – 每页显示条数*/

        //查询构造条件
        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        // 成立的表达式，字段名 和 数值
        if (condition.equals("address")){
            queryWrapper.like(keyword != null && !keyword.equals(""), "address", keyword);
        } else if (condition.equals("appDate")){
            queryWrapper.like(keyword != null && !keyword.equals(""), "app_date", keyword);
        } else {

        }
        Page<Appointment> page = appointmentService.page(new Page<>(pageNum, pageSize), queryWrapper);
        page.getRecords().forEach(en -> {
            // 查询对应的用户和疫苗名称
//            User user = userService.getById(en.getUserId());
            User user = restTemplate.getForObject("http://vecisystem-user/user/getOne/" + en.getUserId(), User.class);

//            Vaccinum vaccinum = vaccinumService.getById(en.getVaccinumId());
//            Vaccinum vaccinum = restTemplate.getForObject("http://localhost:8085/vaccinum/getOne/" + en.getVaccinumId(), Vaccinum.class);

            // 使用了 OpenFeign ,进一步实现了功能的独立，使得根据每个服务可以独立管理起来。
            Vaccinum vaccinum = vacciOpenService.getOne(en.getVaccinumId());
            // 设置到预约信息中
            en.setUser(user);
            en.setVaccinum(vaccinum);
        });

        // 在结果中放一个list集合
        result.put("list", page.getRecords());
        result.put("total", page.getTotal());
        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    // 返回一个 独立的每一个时间和地点，
    @RequestMapping(value = "/listAgrs")
    public String listAddress() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
//        // 定义一个地点的 list
//        List address = new Vector<>();
//        //定义一个时间的 list
//        List time = new Vector<>();
        List<Appointable_list> applist = new LinkedList<>();

        List<Appointable_list> list = appointableListService.list();
        list = list.stream().filter(en -> {
            if (!applist.contains(en)) {
                applist.add(en);
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        result.put("ok", true);
        result.put("address", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description: 查询医护人员
     * @author: deweyMDH
     * @param:
     * @return:
     **/
    @RequestMapping(value = "/listRole")
    public String listRole() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
        List<User> users = new LinkedList<>();

//        // 创建一个条件选择器，查医护人员
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.notIn("role", 0);
//        wrapper.notIn("role", 1);

        // 使用openFeign 服务调度, 向 user 模块，获取医护人员的信息
        List<User> list = userOpenService.getRole();
//        List<User> list = userService.list(wrapper);
        list = list.stream().filter(en -> {
            if (!users.contains(en)) {
                users.add(en);
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        result.put("ok", true);
        result.put("users", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    // 查询所有的预约类型
    @RequestMapping(value = "/listappList")
    public String listAppointableList() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();

        List<Appointable_list> list = appointableListService.list();
        result.put("ok", true);
        result.put("list", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    // 查询所有的用户
    @RequestMapping(value = "/listuser")
    public String listuser() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();

        List<User> list = userOpenService.userAll();
//        List<Appointable_list> list = appointableListService.list();
        result.put("ok", true);
        result.put("list", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description:    新增一个具体的预约记录
     * @author: deweyMDH
     * @param: [appointment]
     * @return: java.lang.String
     **/
//    @PostMapping(value = "/insert")
//    public String insert(Appointment appointment, Long appointablelistId) throws JsonProcessingException {
////         定义一个map来存放json的键值对
//        Map result = new HashMap();
//        // 根据主键，查出一个预约类型
//        Appointable_list appointable_list = appointableListService.getById(appointablelistId);
//        // 把 查出来的 信息，set到预约记录里面
//        appointment.setVaccinumId(appointable_list.getVaccinumId());
//        appointment.setAddress(appointable_list.getAddress());
//        appointment.setAppDate(appointable_list.getAppDate());
//
//        // 保存用户信息
//        boolean one = appointmentService.save(appointment);
//
////        // 创建一个根据appointment，查找相应Appointable_list的条件选择器
////        QueryWrapper<Appointable_list> wrapper = new QueryWrapper<>();
////        wrapper.eq("vaccinum_id", appointment.getVaccinumId());
////        wrapper.eq("address", appointment.getAddress());
////        wrapper.eq("app_date", appointment.getAppDate());
////        Appointable_list appointableList = appointableListService.getOne(wrapper);
//        // 设置某场次，某时间的某种疫苗的预约数加一，剩余量-1
//        appointable_list.setAppNum(appointable_list.getAppNum() + 1);
//        appointable_list.setNums(appointable_list.getNums() - 1);
//        // 修改预约列表的数据
//        appointableListService.updateById(appointable_list);
//        //判断数据库是否有数据
//        if (one != false) {
//            result.put("ok", true);
//            result.put("appointment", appointment);
//        } else {
//            result.put("ok", false);
//            result.put("message", "错误");
//        }
//        // 返回
//        return objectMapper.writeValueAsString(result);
//    }

    /**
     * @description:    新增一个具体的预约记录
     * @author: deweyMDH
     * @param: [appointment]
     * @return: java.lang.String
     **/
    @PostMapping(value = "/insert")
    public String insertAppointment(Appointable_list appointableList, Long userid) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        Appointment appointment = new Appointment();

        appointment.setUserId(userid);
        appointment.setVaccinumId(appointableList.getVaccinumId());
        appointment.setAddress(appointableList.getAddress());
        appointment.setAppDate(appointment.getAppDate());
        // 创建一个此刻的时间，格式是 yy-mm-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String PostTime = sdf.format(now);
        appointment.setPostTime(PostTime);

        appointment.setStatus(0);
        // 查询所有的医护人员
        List<User> role = userOpenService.getRole();
        User userDoc = role.get(new Random().nextInt(role.size()));
        appointment.setDocId(userDoc.getId());

        boolean save = appointmentService.save(appointment);
        // 设置某场次，某时间的某种疫苗的预约数加一，剩余量-1
        appointableList.setAppNum(appointableList.getAppNum() + 1);
        appointableList.setNums(appointableList.getNums() - 1);
        // 修改预约列表的数据
        boolean one = appointableListService.updateById(appointableList);
        //判断数据库是否有数据
        if (save!= false && one != false) {
            result.put("ok", true);
            result.put("appointment", appointment);
        } else {
            result.put("ok", false);
            result.put("message", "错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }

    @RequestMapping(value = "/update")
    public String updateAppointList(Long id) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        Appointment one = appointmentService.getById(id);
        // 设置预约记录的状态为1
        Integer status = one.getStatus();
        if (status == 0){
            one.setStatus(1);
        } else if (status == 1){
            one.setStatus(0);
        }else {
            one.setStatus(1);
        }
        boolean two = appointmentService.updateById(one);
        //判断数据库是否有数据
        if (two != false) {
            result.put("ok", true);
            result.put("appointment", two);
        } else {
            result.put("ok", false);
            result.put("message", "接种修改错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }


    /**
     * @description: 根据主键，删除相应的预约
     * @author: deweyMDH
     * @param: [Id]
     * @return: java.lang.String
     **/
    @DeleteMapping(value = "/delete/{id}")
    public String deleteAppointment(@PathVariable(value = "id") Integer Id) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        boolean one = appointmentService.removeById(Id);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointment", Id);
        } else {
            result.put("ok", false);
            result.put("message", "删除预约错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }
}
